import { isNumber } from "@/utils";
import { Form, type FormItemProps, Grid } from "@arco-design/web-react";
import type { PropsWithChildren, ReactNode } from "react";
import type { Breakpoint } from "../types";
import { type SeContextType, useSeContext } from "./context";

type SeProps<TModel> = PropsWithChildren<
	SeContextType & Omit<FormItemProps<TModel>, "labelCol" | "wrapperCol">
>;

const TOTAL_COLUMNS = 24;

export default function Se<TModel>({
	children,
	col,
	labelWidth,
	required,
	rules,
	...rest
}: SeProps<TModel>): ReactNode {
	const context = useSeContext();

	const seCol = col ?? context?.col ?? 1;

	const breakpointCols: Record<Breakpoint, number> = {} as Record<
		Breakpoint,
		number
	>;
	if (!isNumber(seCol)) {
		for (const k of Object.keys(seCol)) {
			breakpointCols[k as Breakpoint] = TOTAL_COLUMNS / seCol[k as Breakpoint]!;
		}
	}
	const colProps = {
		span: isNumber(seCol) ? TOTAL_COLUMNS / seCol : undefined,
		...breakpointCols,
	};

	const seLabelWidth = labelWidth ?? context?.labelWidth ?? 90;

	if (required) {
		rules = [
			{
				required: true,
				message: `${rest.label || "该字段"}不能为空`,
			},
			...(rules ?? []),
		];
	}

	return (
		<Grid.Col {...colProps}>
			<Form.Item<TModel>
				labelCol={{ flex: "none", style: { width: seLabelWidth } }}
				required={required}
				rules={rules}
				{...rest}
			>
				{children}
			</Form.Item>
		</Grid.Col>
	);
}
